<template>
  <div class="child">
    <div class="product-info">
      <p>商品名称：{{ productName }}</p>
      <p>商品价格：¥{{ productPrice }}</p>
      <button @click="addToCart">添加到购物车</button>
    </div>
  </div>
</template>

<script>
export default {
  // 接收父组件传递的props
  props: {
    productName: {
      type: String,
      required: true
    },
    productPrice: {
      type: Number,
      required: true,
      validator: (value) => {
        return value > 0;
      }
    }
  },
  methods: {
    // 向父组件传递数据
    addToCart() {
      // 触发父组件的自定义事件，并传递商品信息
      this.$emit('add-to-cart', {
        name: this.productName,
        price: this.productPrice
      });
    }
  }
};
</script>

<style scoped>
.child {
  padding: 15px;
  background: #f9f9f9;
  border-radius: 4px;
}
button {
  margin-top: 10px;
  padding: 8px 16px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:hover {
  background: #359e75;
}
</style>